package whf.framework.datasource.impl;

import java.util.Collection;
import java.util.Iterator;

import whf.framework.datasource.DataRow;
import whf.framework.datasource.DataSource;
import whf.framework.datasource.DataSourceException;
import whf.framework.service.FindService;

/**
 * @author king
 * @modify 2007-12-14 下午01:07:26
 */
public abstract class AbstractDataSource<E extends DataRow> implements DataSource<E> {
	protected Iterator<E> iterator;
	protected transient E currentObject;
	protected transient FindService service;
	protected transient int totalRowCount = -1;
	protected transient Collection<E> dataCollection;
	
	/* (non-Javadoc)
	 * @see whf.framework.datasource.DataSource#size()
	 */
	public int size() throws DataSourceException {
		return this.getDataSource().size();
	}

	/* (non-Javadoc)
	 * @see whf.framework.datasource.DataSource#iterator()
	 */
	public Iterator<E> iterator() {
		this.iterator = this.getDataSource().iterator();
		return this.iterator;
	}

	// ------------- iterator implements ------------------
	/* (non-Javadoc)
	 * @see java.util.Iterator#hasNext()
	 */
	public boolean hasNext() {
		if(this.iterator == null) this.iterator =this.getDataSource().iterator();
		return this.iterator.hasNext();
	}

	/* (non-Javadoc)
	 * @see java.util.Iterator#next()
	 */
	public E next() {
		if(this.iterator == null) this.iterator =this.getDataSource().iterator();
		this.currentObject = this.iterator.next();
		return this.currentObject;
	}

	/* (non-Javadoc)
	 * @see java.util.Iterator#remove()
	 */
	public void remove() {
		if(this.iterator == null) this.iterator =this.getDataSource().iterator();
		this.iterator.remove();
	}

	// --------------------- object implements ------------------------------
	/* (non-Javadoc)
	 * @see whf.framework.datasource.DataSource#getData()
	 */
	public E getCurrent() {
		return this.currentObject;
	}

	/* (non-Javadoc)
	 * @see whf.framework.datasource.DataSource#getDataSource()
	 */
	public Collection<E> getDataSource() throws DataSourceException {
		return this.dataCollection;
	}

	/* (non-Javadoc)
	 * @see whf.framework.datasource.DataSource#getTotalRowCount()
	 */
	public int getTotalRowCount() throws DataSourceException {
		if(this.totalRowCount >= 0)
			return this.totalRowCount;
		else if(this.dataCollection != null) 
			return this.dataCollection.size();
		else
			throw new DataSourceException("Not implemented yes!");
	}
}
